<template>
  <Header />
  <div class="consult">
    <!-- audio -->
    <audio id="VoicePlayer" src="http://localhost:8080/audio/lfasr.wav"></audio>
    <!-- 消息显示在这里 -->
    <main class="contents" @click="showEmoji=false">
      <ul id="ContentArea">
      </ul>
    </main>
    <img src="../../assets/Recoding.gif" v-show="isStart" class="voiceImg"/>
    <!-- 底部的输入框表情和语音 -->
    <footer class="actionbar">
      <!-- 语音按钮 -->
      <div class="voice">
        <el-button icon="el-icon-microphone" circle @click="voiceAnalyse"></el-button>
      </div>
      <!-- 输入框 -->
      <input class="my_text" type="text" ref="text"  />
      <!-- 表情按钮 -->
      <div class="emoji">
        <el-button icon="el-icon-picture-outline-round" circle @click="showEmoji=!showEmoji"></el-button>
      </div>
      <!-- 发送按钮 -->
      <el-button icon="el-icon-s-promotion" circle @click="send()"></el-button>
      <!-- 录音按钮 -->
      <el-button icon="el-icon-mic" circle @click="recording"></el-button>
    </footer>
    <!-- 表情界面 -->
    <div class="emoji_page" v-if="showEmoji">
      <div class="emoji_page_categorys">
        <ul>
          <li v-for="(item, index) in EmojisList" :key="index" @click="GetEmoji(item.unicode)">
            <img :src="item.src"/>
          </li>
        </ul>
        <div class="dots_area">
          <el-pagination
            style="margin-left:-40px"
            small
            layout="prev, pager, next"
            :total="50"
            @current-change="EmojiInit">
          </el-pagination>
        </div>
      </div>
    </div>
    <!-- 语音转写 -->
    <iframe src="http://localhost:8080/Voice" style="display:none" id="myVoice"  allow="microphone;camera;midi;encrypted-media;"></iframe>
    <!-- 录音遮罩 -->
    <van-action-sheet v-model:show="show" title="请说话">
      <div class="recording-voice">
        <i class="el-icon-mic" @click="recorded"></i>
        <img src="../../assets/Recoding.gif" style="width:180px;height:100px;position: absolute;bottom:50px;left:50%;margin-left:-90px"/>
      </div>
    </van-action-sheet>
  </div>
  <Footer />
</template>

<script>
import Header from "../Header";
import Footer from "../Footer";
import "element-plus/lib/theme-chalk/index.css";
import "../../assets/js/emoji";
import "../../assets/js/emoji-list-with-image";
import "../../assets/js/punycode";
import '../../assets/js/punycode.min.js'
import { getEmojiList } from '../../assets/js/emoji-list-with-image';
export default {
  name: "Consult",
  data() {
    return {
      websocket: null,
      showEmoji:false,
      EmojisList:[],
      isStart:false,
      show:false,
      //录音实例
      mediaRecorder:null,
      voice:[],
      blob:null,
    };
  },
  components: {
    Header,
    Footer,
  },
  methods: {
    // 获取某一页的Emoji
    EmojiInit:function(i){
      this.EmojisList=[]
      let page
      i!==undefined?page=i-1:page=0
      let emojiList=getEmojiList()[page];
      emojiList.forEach(element => {
        let emos=element
        let unicode=emos[1]
        let imgsrc='data:image/png;base64,' + emos[2]
        let EmojiData={}
        EmojiData['src']=imgsrc
        EmojiData['unicode']="0x"+unicode
        this.EmojisList.push(EmojiData)
      });
    },
    // 从表情界面获取emoji
    GetEmoji:function(unicode){
      let text=this.$refs.text
      let EmoArray;
      let EmojiCode;
      if(unicode.length<7){
        EmoArray=unicode
        EmojiCode=String.fromCharCode(EmoArray)
        console.log(EmojiCode)
        this.insertText(EmojiCode)
      }
      else{
        EmoArray=this.findSurrogatePair(unicode)
        console.log(EmoArray)
        let temp=""
        for(let i=0;i<EmoArray.length;i++){
          temp+="\\u"
          temp+=EmoArray[i]
        }
        EmojiCode=unescape(temp.replace(/\\u/g,"%u"))
        console.log(EmojiCode)
        this.insertText(EmojiCode)
      }
    },
    //做拼接
    findSurrogatePair:function(point){
      let offset = point - 0x10000,
      lead = 0xd800 + (offset >> 10),
      trail = 0xdc00 + (offset & 0x3ff);
      return [lead.toString(16), trail.toString(16)];
    },
    //光标处插入
    insertText:function(innerText){
      let text=this.$refs.text
      let startPoint=text.selectionStart
      let endPoint= text.selectionEnd
      if(startPoint===undefined || endPoint===undefined) return
      text.value=text.value.substring(0,startPoint)+innerText+text.value.substring(endPoint)
      text.focus()
      text.selectionStart=startPoint+innerText.length
      text.selectionEnd=startPoint+innerText.length
    },
    //语音转写
    voiceAnalyse:function(){
      this.isStart=!this.isStart
      let text=this.$refs.text
      if(this.isStart) text.value=""
      let myFrame=document.getElementById("myVoice")
      let startBtn=myFrame.contentWindow.document.getElementById("taste_button")
      let resultText=myFrame.contentWindow.document.getElementById("result_output")
      startBtn.click()
      if(this.isStart){
        resultText.addEventListener("DOMNodeInserted",()=>{
          text.value=resultText.innerText
        });
        startBtn.addEventListener("DOMNodeInserted",()=>{
          if(startBtn.classList.contains("status-end")){
            console.log("Over")
            this.isStart=false
          }
        })
      }
    },
    //发消息
    send:function(){
      let message=this.$refs.text.value
      if(message==="") return
      this.websocket.send(message)
      this.$refs.text.value=""
      this.$refs.text.focus()
    },
    setMessageInnerHTML:function(innerHTML,classname) {
      //document.getElementById('ContentArea').innerHTML += innerHTML + '<br/>';
      let ul = document.getElementById("ContentArea")
      let text=document.createTextNode(innerHTML)
      let li = document.createElement('li')
      li.appendChild(text)
      ul.appendChild(li).className=classname
    },
    setVoiceInnerHTML:function(src,classname){
      let ul = document.getElementById("ContentArea")
      let li = document.createElement('li')
      li.setAttribute("data-src",src)
      li.classList.add("divAudio")
      li.classList.add(classname)
      li.addEventListener("click",()=>{
        document.getElementById("VoicePlayer").src=li.getAttribute("data-src")
        document.getElementById("VoicePlayer").play()
      })
      ul.appendChild(li)
    },
    // 先获取权限
    getAuthority:function(){
      if(navigator.mediaDevices.getUserMedia){
        const constraints={audio:true};
        navigator.mediaDevices.getUserMedia(constraints).then(stream=>{
          console.log("授权成功")
          this.mediaRecorder=new MediaRecorder(stream)
          console.log(this.mediaRecorder)
          this.mediaRecorder.ondataavailable=(result)=>{
            console.log(result)
            this.voice.push(result.data)
          }
          this.mediaRecorder.onstop=async()=>{
            this.blob=new Blob(this.voice,{type:"audio/webm;codecs=opus"})
            this.voice=[]
            console.log(this.blob)
            let url=window.URL.createObjectURL(this.blob)
            document.getElementById("VoicePlayer").src=url
            document.getElementById("VoicePlayer").play()
            let data=new FormData()
            data.append("file",this.blob)
            try{
              let response=await fetch("http://localhost:8080/uploadVoice",{
                method:"POST",
                body:data
              })
              let result=await response.json()
              this.websocket.send(result)
            }
            catch(e){
              console.error(e)
            }
          }
        },
        ()=>{
          console.error("授权失败了")
        });
      }
      else{
        console.error("浏览器不支持")
      }
    },
    //录音哦
    recording:function(){
      this.show=!this.show
      this.mediaRecorder.start()
      console.log(this.mediaRecorder.state)
    },
    //录音结束咯然后去上传
    recorded:function(){
      this.show=!this.show
      this.mediaRecorder.stop()
      console.log(this.mediaRecorder.state)
    }
  },
  //退出当前组件时触发
  beforeUnmount() {
    this.websocket.close();
  },
  mounted(){
    this.EmojiInit()
    this.getAuthority()
  },
  created() {
    document.domain="localhost"
    const PID=(Math.round(Math.random()*100)).toString()
    this.websocket = new WebSocket(
      "ws://localhost:8080/websocket/" + PID
    );
    console.log(this.websocket);

    this.websocket.onopen = () => {
      this.websocket.send("有新用户加入了聊天");
    };

    this.websocket.onmessage=(event)=>{
      let point = event.data.indexOf(":")
      let id=event.data.substring(0,point)
      let message=event.data.substring(point+1)
      console.log(message.substring(message.length-4))
      if(message.substring(message.length-4)===".mp3" && PID===id){
        this.setVoiceInnerHTML(message,"YouContent")
      }
      else if(message.substring(message.length-4)===".mp3" && PID!==id){
        this.setVoiceInnerHTML(message,"OtherContent")
      }
      else{
        if(message==="有新用户加入了聊天"){
          this.setMessageInnerHTML(message,"SystemNode")
        }
        else if(PID===id){
          this.setMessageInnerHTML(message,"YouContent")
        }
        else{
          this.setMessageInnerHTML(message,"OtherContent")
        }
      }
    }
  },
};
</script>

<style scoped>
.emoji_page{
  width: 400px;
  height: 350px;
  position: absolute;
  background-color: white;
  box-sizing: border-box;
  border-radius: 19px;
  bottom: 50px;
  overflow: hidden;
}
.emoji_page ul{
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 10px 10px 10px 10px;
}
.emoji_page ul li{
  height: 23px;
  width: 23px;
  float: left;
  margin: 3px 3px 3px 3px;
  vertical-align: middle;
}
.emoji_page_categorys{
  width: 100%;
  height: 100%;
}
.consult {
  width: 100%;
  height: 85vh;
  margin-top: 50px;
  display: flex;
  flex-direction: column;
  font-family: "icomoon"!important;
  position: relative;
}
.contents{
  width: 100%;
  height: 575px;
  box-sizing: border-box;
  padding: 0 15px 0 15px;
  overflow: auto;
}
.actionbar{
  position: relative;
  width: 100%;
  height: 50px;
  box-sizing: border-box;
  background: #409EFF;
  vertical-align: middle;
}
.my_text{
  padding-left: 20px;
  border: none;
  width: 190px;
  height: 30px;
  border-radius: 19px;
  color: black;
  margin-top: 10px;
  margin-left: 2px;
  margin-right: 10px;
}
.voice{
  height: 100%;
  width: 50px;
  float: left;
  box-sizing: border-box;
  padding-top: 7px;
}
.emoji{
  float: left;
  height: 100%;
  width:40px;
  box-sizing: border-box;
  padding-top: 7px;
}
.emoji img{
  width: 30px;
  height: 30px;
}
.dots_area{
  position: absolute;
  width: 100px;
  height: 30px;
  bottom: 0;
  left: 50%;
  margin-left: -50px;
}
.voiceImg{
  position: absolute;
  width: 120px;
  height: 70px;
  bottom: 50px;
  z-index: 9999999;
}
.recording-voice{
  height: 300px;
  box-sizing: border-box;
  widows: 100%;
  padding: 0 20px 0 20px;
}
.recording-voice i{
  font-size: 50px;
  width: 150px;
  height: 150px;
  border: 1px solid lightgrey;
  border-radius: 75px;
  line-height: 150px;
}
</style>
